import 'package:flutter/material.dart';
import 'package:kasax/commons/commons.dart';
import 'package:rxdart/rxdart.dart';

/// 常用操作符练习
/// 主要是用于处理在observable上的数据
class RxDartOperatorDemoHome extends StatefulWidget {
  const RxDartOperatorDemoHome({Key? key}) : super(key: key);

  @override
  _RxDartOperatorDemoHomeState createState() => _RxDartOperatorDemoHomeState();
}

class _RxDartOperatorDemoHomeState extends State<RxDartOperatorDemoHome> {
  BehaviorSubject<List<String>> _behaviorSubject = BehaviorSubject();

  @override
  void initState() {
    super.initState();
    _behaviorSubject.add([
      'map',
      'periodic',
      'interval',
      'timer',
      'concat',
      'where',
      'debounce',
      'expand',
      'mergeWith',
      'Distinct',
      'zipwith',
      'CombineLatest',
      'every',
      'AsyncMap'
    ]);
  }

  @override
  void dispose() {
    super.dispose();
    _behaviorSubject.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("RxDart常用操作符"),
      ),
      body: StreamBuilder(
        stream: _behaviorSubject,
        builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
          print(
              "snapshot-state: ${snapshot.connectionState} - ${snapshot.data}");
          if (snapshot.hasData) {
            if (snapshot.data!.isEmpty) {
              return buildLoadingWidget();
            }
            return Padding(
              padding:
                  EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: 3.0,
                  crossAxisSpacing: 3.0,
                ),
                itemBuilder: (context, index) {
                  return Container(
                    padding: EdgeInsets.all(4),
                    alignment: Alignment.center,
                    color: Colors.primaries[index % snapshot.data!.length],
                    child: FlatButton(
                      child: Text(
                        "${snapshot.data![index]}",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () {
                      },
                    ),
                  );
                },
                itemCount: snapshot.data!.length,
              ),
            );
          } else {
            return buildLoadingWidget();
          }
        },
      ),
    );
  }
}
